#!/bin/python3
import argparse
import sys
import os
import zipfile
import json
import urllib.request
from urllib.parse import urlparse
from pathlib import Path


def report(count, block_size, total_size):
    progress_size = int(count * block_size)
    percent = min(int(count * block_size * 100 / total_size), 100)
    sys.stdout.write("\r%d%%\t%.3f MB" %
                     (percent, progress_size / (1024 * 1024)))
    sys.stdout.flush()


def handle_url(url):
    path = Path().absolute()
    download_url = url + '/files/latest/'
    print(download_url)
    extract_zip(download(download_url, path))


def extract_zip(path):
    folder_name = os.path.splitext(path)[0]
    if not os.path.exists(folder_name):
        os.mkdir(folder_name)
    zip_file = zipfile.ZipFile(path)
    zip_file.extractall(folder_name)
    zip_file.close()
    if not os.path.exists(Path(folder_name + '/overrides/mods')):
        os.mkdir(Path(folder_name + '/overrides/mods'))
    download_mods(folder_name)


def download(url, save_path):
    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    download_url = urllib.request.urlopen(req).geturl()
    parsed_url = urlparse(download_url)
    file_name = os.path.basename(parsed_url.path)
    save_path = os.path.join(save_path, file_name)
    urllib.request.urlretrieve(download_url, save_path, reporthook=report)
    return save_path


def download_mods(folder_name):
    with open(os.path.join(folder_name, 'manifest.json'), 'r') as f:
        json_data = json.load(f)

    minecraft_version = json_data['minecraft']['version']
    forge_version = json_data['minecraft']['modLoaders'][0]['id']
    print('\n\nMinecraft Version : ' + minecraft_version)
    print('Forge Version : ' + forge_version)

    mod_len = len(json_data['files'])
    print('Total ' + str(mod_len) + ' mods have found !')

    mod_counter = 1
    for mod in json_data['files']:
        download_url = 'https://minecraft.curseforge.com/projects/' + \
            str(mod['projectID']) + '/files/' + str(mod['fileID']) + '/download'
        req = urllib.request.Request(download_url, headers={'User-Agent': 'Mozilla/5.0'})
        download_url = urllib.request.urlopen(req).geturl()
        print(download_url)
        parsed_url = urlparse(download_url)
        file_name = os.path.basename(parsed_url.path)
        sys.stdout.write(
            '\n[' +
            str(mod_counter) +
            '/' +
            str(mod_len) +
            '] ' +
            file_name +
            '\n')
        urllib.request.urlretrieve(
            download_url,
            os.path.join(
                folder_name,
                'overrides',
                'mods',
                file_name),
            reporthook=report)
        mod_counter = mod_counter + 1


def main():
    parser = argparse.ArgumentParser(description='Curse Modpack Downloader')
    parser.add_argument("-i", "--input", dest="filename")
    parser.add_argument("url", nargs='?')
    args = parser.parse_args()
    if args.filename:
        extract_zip(args.filename)
    elif args.url:
        handle_url(args.url)


if __name__ == '__main__':
    main()
